require('dotenv').config() // 加载环境变量
const express = require('express')
const cors = require('cors')
const app = express()

// 使用 CORS 中间件
app.use(cors())
// 添加请求体解析中间件
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

// 添加请求日志中间件
app.use((req, res, next) => {
  console.log(`收到请求: ${req.method} ${req.url}`)
  next()
})

// 导入用户相关路由
const usersRouter = require('./routes/users')
app.use('/7a/api/users', usersRouter)
// 导入文件上传路由
const uploadRouter = require('./routes/upload')
app.use('/7a/api/upload', uploadRouter)

// 静态文件服务配置
const path = require('path')
app.use('/7a/api/uploads', express.static(path.join(__dirname, '../uploads')))

// 博客文章相关路由
const articleRoutes = require('./routes/article')
app.use('/7a/api/article', articleRoutes)

// 评论相关路由
const commentRoutes = require('./routes/comments')
app.use('/7a/api/comment', commentRoutes)

// ai相关路由
const aiRouter = require('./routes/ai')
app.use('/7a/api/ai', aiRouter)

// 图床相关路由
const picturebedRouter = require('./routes/picturebed')
app.use('/7a/api/picture', picturebedRouter)

// 大黄蜂图床相关路由
const dhfImgBedRouter = require('./routes/dhfImgBed')
app.use('/7a/api/dhfImgBed', dhfImgBedRouter)

// 字典相关路由
const dicRouter = require('./routes/dic')
app.use('/7a/api/dic', dicRouter)

// 测试接口服务
app.get('/7a/api/test', (req, res) => {
  res.json({ message: '服务正在运行' })
})

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('发生错误:', err)
  res.status(500).json({ message: err.message })
})

const port = process.env.PORT || 3001
app.listen(port, '0.0.0.0', () => {
  console.log(`服务器运行在端口 ${port}，监听所有网络接口`)
})
